﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.UI.HtmlControls;
using QD.Utils;

namespace QD.Web.Upload
{
    public class Upload
    {
        private static Random random;

        private static ActionResultUpload CheckCfg(HttpPostedFile httpfile, UploadFolderCfg config)
        {
            ActionResultUpload upload = new ActionResultUpload();
            if (!config.AllowUpload)
            {
                upload.AddErrorLine("The current system do not upload");
                return upload;
            }
            if ((httpfile == null) || (httpfile.ContentLength == 0))
            {
                upload.AddErrorLine("File is empty or length is 0");
                return upload;
            }
            upload.FileSize = httpfile.ContentLength;
            if (upload.FileSize > config.FileMaxSize * 1024)
            {
                upload.AddErrorLine("Files can be the biggest " + config.FileMaxSize + " K");
                return upload;
            }
            upload.Ext = IOUtils.GetFileExtName(httpfile.FileName);
            if (!config.AllowExt.ToLower().Split(new char[] { ',' }).Contains<string>(upload.Ext.ToLower()))
            {
                upload.AddErrorLine("Only allowed to upload suffix " + config.AllowExt + " files");
                return upload;
            }
            DateTime datetime = DateTime.Now;
            if (config.FolderStyle == FolderNameStyle.With_Year_Month)
            {
                upload.SaveAt = datetime.ToString("yyyy") + "/" + datetime.ToString("MM") + "/";
            }
            else if (config.FolderStyle == FolderNameStyle.With_Year_Month_Day)
            {
                upload.SaveAt = datetime.ToString("yyyy") + "/" + datetime.ToString("MM") + "/" + datetime.ToString("dd") + "/";
            }
            else
            {
                upload.SaveAt = "";
            }
            return upload;
        }
        private static Bitmap Cut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight, int destWidth, int destHeight)
        {
            if (b == null)
            {
                return null;
            }
            int width = b.Width;
            int height = b.Height;
            if ((StartX >= width) || (StartY >= height))
            {
                return null;
            }
            if ((StartX + iWidth) > width)
            {
                iWidth = width - StartX;
            }
            if ((StartY + iHeight) > height)
            {
                iHeight = height - StartY;
            }
            try
            {
                Bitmap image = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
                Graphics graphics = Graphics.FromImage(image);
                graphics.DrawImage(b, new Rectangle(0, 0, destWidth, destHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
                graphics.Dispose();
                return image;
            }
            catch
            {
                return null;
            }
        }

        protected static string GetNewFileName()
        {
            random = new Random((int)DateTime.Now.Ticks);
            int num = Environment.TickCount & int.MaxValue;
            return (num.ToString() + random.Next(1000, 9999).ToString());
        }

        public static string SaveCutPic(string pPath, UploadFolderCfg config, int destPointX, int destPointY, int cutWidth, int cutHeight, int srcPointX, int srctPointY, int outputWidth, int outputHeight)
        {
            if (!Directory.Exists(config.RootPath))
            {
                Directory.CreateDirectory(config.RootPath);
            }
            string str = config.GetFileName(GetNewFileName()) + ".jpg";
            string path = config.RootPath + Path.DirectorySeparatorChar + str;
            System.Drawing.Image original = System.Drawing.Image.FromFile(pPath);
            Bitmap srcImage = new Bitmap(original);
            Bitmap bitmap2 = QD.Web.Upload.Image.CutImageRedraw(srcImage, destPointX, destPointY, cutWidth, cutHeight, srcPointX, srctPointY, outputWidth, outputHeight);
            original.Dispose();
            srcImage.Dispose();
            if (System.IO.File.Exists(path))
            {
                System.IO.File.SetAttributes(path, FileAttributes.Normal);
                System.IO.File.Delete(path);
            }
            bitmap2.Save(path, ImageFormat.Jpeg);
            bitmap2.Dispose();
            return str;
        }
        public static string SaveCutPic2(string pPath, UploadFolderCfg config, int StartX, int StartY, int iWidth, int iHeight, int destWidth, int destHeight)
        {
            if (!Directory.Exists(config.RootPath))
            {
                Directory.CreateDirectory(config.RootPath);
            }
            string str = config.GetFileName(GetNewFileName()) + ".jpg";
            string path = config.RootPath + Path.DirectorySeparatorChar + str;
            System.Drawing.Image image = System.Drawing.Image.FromFile(pPath);
            Bitmap bitmap = Cut(image as Bitmap, StartX, StartY, iWidth, iHeight, destWidth, destHeight);
            image.Dispose();
            if (System.IO.File.Exists(path))
            {
                System.IO.File.SetAttributes(path, FileAttributes.Normal);
                System.IO.File.Delete(path);
            }
            bitmap.Save(path, ImageFormat.Jpeg);
            bitmap.Dispose();
            return str;
        }
        public static IList<ActionResultUpload> UploadFile(HttpFileCollection httpFiles, UploadFolderCfg config)
        {
            IList<ActionResultUpload> list = new List<ActionResultUpload>();
            for (int i = 0; i < httpFiles.Count; i++)
            {
                list.Add(UploadFile(httpFiles[i], config));
            }
            return list;
        }
        public static IList<ActionResultUpload> UploadFile(HtmlInputFile[] htmlFiles, UploadFolderCfg config)
        {
            IList<ActionResultUpload> list = new List<ActionResultUpload>();
            foreach (HtmlInputFile file in htmlFiles)
            {
                list.Add(UploadFile(file, config));
            }
            return list;
        }

        public static ActionResultUpload UploadFile(HttpPostedFile httpfile, UploadFolderCfg config)
        {
            ActionResultUpload upload = CheckCfg(httpfile, config);
            if (!upload.IsError)
            {
                if (!Directory.Exists(config.RootPath + upload.SaveAt))
                {
                    Directory.CreateDirectory(config.RootPath + upload.SaveAt);
                }
                upload.FileName = Path.GetFileName(httpfile.FileName);
                string rootPath = config.RootPath;
                upload.SaveName = config.GetFileName(GetNewFileName());
                try
                {
                    httpfile.SaveAs(rootPath + upload.SaveAt + upload.SaveName + upload.Ext);
                }
                catch (Exception exception)
                {
                    upload.AddErrorLine(exception.Message);
                }
            }
            return upload;
        }
        public static ActionResultUpload UploadFile(HtmlInputFile htmlFile, UploadFolderCfg config)
        {
            return UploadFile(htmlFile.PostedFile, config);
        }
        public static IList<ActionResultUpload> UploadFile(HttpFileCollection httpFiles, UploadFolderCfg config, string fileKey)
        {
            IList<ActionResultUpload> list = new List<ActionResultUpload>();
            for (int i = 0; i < httpFiles.Count; i++)
            {
                if (httpFiles.AllKeys[i] == fileKey)
                {
                    list.Add(UploadFile(httpFiles[i], config));
                }
            }
            return list;
        }
        public static ActionResultUpload UploadFirstFile(HttpFileCollection httpFiles, UploadFolderCfg config, string fileKey)
        {
            for (int i = 0; i < httpFiles.Count; i++)
            {
                if (httpFiles.AllKeys[i] == fileKey)
                {
                    return UploadFile(httpFiles[i], config);
                }
            }
            return null;
        }
        public static IList<ActionResultUpload> UploadImgFile(HttpFileCollection httpFiles, UploadFolderCfg config, ImageFileCfg imgCfg)
        {
            IList<ActionResultUpload> list = new List<ActionResultUpload>();
            for (int i = 0; i < httpFiles.Count; i++)
            {
                list.Add(UploadImgFile(httpFiles[i], config, imgCfg));
            }
            return list;
        }

        public static ActionResultUpload UploadImgFile(HttpPostedFile httpfile, UploadFolderCfg config, ImageFileCfg imgCfg)
        {
            ActionResultUpload upload = CheckCfg(httpfile, config);
            if (!upload.IsError)
            {
                if (!Directory.Exists(config.RootPath + upload.SaveAt))
                {
                    Directory.CreateDirectory(config.RootPath + upload.SaveAt);
                }
                upload.FileName = Path.GetFileName(httpfile.FileName);
                string rootPath = config.RootPath;
                upload.SaveName = config.GetFileName(GetNewFileName());
                if (imgCfg == null)
                {
                    httpfile.SaveAs(rootPath + upload.SaveAt + upload.SaveName + upload.Ext);
                }
                else
                {
                    System.Drawing.Image original = System.Drawing.Image.FromStream(httpfile.InputStream);
                    try
                    {
                        if ((imgCfg.ImageMaxHeigth != 0) || (imgCfg.ImageMaxWidth != 0))
                        {
                            if ((imgCfg.ImageMaxHeigth != 0) && (imgCfg.ImageMaxHeigth < original.Height))
                            {
                                upload.AddWarningLine("Images allow for maximum height:" + imgCfg.ImageMaxHeigth);
                            }
                            if ((imgCfg.ImageMaxWidth != 0) && (imgCfg.ImageMaxWidth < original.Width))
                            {
                                upload.AddWarningLine("Images allow for maximum width:" + imgCfg.ImageMaxWidth);
                            }
                            Size newSize = Image.ResizeImage(original.Width, original.Height, (imgCfg.ImageMaxWidth != 0) ? imgCfg.ImageMaxWidth : 0x7fff, (imgCfg.ImageMaxHeigth != 0) ? imgCfg.ImageMaxHeigth : 0x7fff);
                            System.Drawing.Image image2 = new Bitmap(original, newSize);
                            image2.Save(rootPath + upload.SaveAt + upload.SaveName + upload.Ext, Image.GetFormat(httpfile.FileName));
                            image2.Dispose();
                        }
                        else
                        {
                            original.Save(rootPath + upload.SaveAt + upload.SaveName + upload.Ext, Image.GetFormat(httpfile.FileName));
                        }
                        if (upload.IsError)
                        {
                            return upload;
                        }
                    }
                    catch (Exception exception)
                    {
                        upload.AddErrorLine(exception.Message);
                    }
                    finally
                    {
                        original.Dispose();
                    }
                }
            }
            return upload;
        }















































    }
}
